<template>
  <div>
    <el-dialog
      append-to-body
      :title="topic_title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      class="mt-dialog"
      width="50%"
      top="10px;"
      @close="close"
    >
      <div v-if="viewDetail">
        <h3>{{ viewTitle }}</h3>
        <el-button style="float: right" type="danger" @click="viewDetail=false">返 回</el-button>
        <hr>
        <div style="display: block; font-size: 14px" v-html="viewdescription" />
        <el-button type="danger" @click="viewDetail=false">返 回</el-button>
      </div>
      <div v-else>
        <el-tabs v-model="activeName" @tab-click="handleClickTab">
          <el-tab-pane label="POST列表" name="first">
            <div v-loading="listLoading" class="top">
              <el-input
                v-model="kwInput"
                size="mini"
                placeholder="输入 任意字符 进行筛选"
                class="input-with-select"
                clearable
                @keyup.native.enter="handleSearch"
              >
                <el-button slot="append" size="mini" icon="el-icon-search" @click="handleSearch">搜索</el-button>
              </el-input>
              <el-button
                size="mini"
                type="primary"
                class="el-icon-plus add-btn"
                :disabled="listLoading"
                @click="handleAction('create', '添加文章')"
              >添加文章
              </el-button>
            </div>
            <el-table
              v-loading.body="listLoading"
              :data="data"
              border
              fit
              highlight-current-row
              style="width: 100%"
              @sort-change="handleSort"
            >
              <el-table-column align="left" label="POST" prop="post__title" sortable="custom">
                <template slot-scope="scope">
                  <a v-if="scope.row.post_id" :href="'/#/cms/post/edit/' + scope.row.post_id" target="_blank">{{ scope.row.post__title }}</a>
                </template>
              </el-table-column>
              <el-table-column align="left" label="长度" prop="post__word_count" sortable="custom" width="100" />
              <el-table-column align="left" label="作者" prop="owner__username" sortable="custom" width="100" />
              <el-table-column align="right" label="操作" sortable="custom" width="180">
                <template slot-scope="scope">
                  <a v-if="scope.row.post_id" :href="'/#/cms/post/edit/' + scope.row.post_id" target="_blank">编辑POST</a>
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleAction('delete', scope.row)">删除</el-button>

                </template>
              </el-table-column>
            </el-table>
            <!--            <el-card class="box-card" shadow="hover" v-for='item in data' :key="item.id"-->
            <!--                     style="float: left; margin-right: 10px;margin-bottom: 10px;width: 350px">-->
            <!--              <div slot="header" class="clearfix">-->
            <!--                <span>ID:{{item.post__title}}</span>-->
            <!--                <el-button size="mini" style="float: right; padding: 3px 0" type="text" @click="handleAction('edit', item)">修改</el-button>-->
            <!--                <el-button size="mini" style="float: right; padding: 3px 0" type="text" @click="handleAction('delete', item)">删除</el-button>-->
            <!--              </div>-->
            <!--              <div class="bottom clearfix">-->
            <!--                <time class="time">{{ item.create_at.split('T')[0] }}</time>-->
            <!--&lt;!&ndash;                <el-button type="text" class="button" @click="handleViewDetail(item)">查看详情</el-button>&ndash;&gt;-->
            <!--                <a v-if="item.post_id" :href="'/#/cms/post/' + item.post_id" target="_blank">查看文章</a>-->
            <!--                <a v-else href="/#/cms/post/" target="_blank">编辑文章</a>-->
            <!--              </div>-->
            <!--            </el-card>-->

            <el-pagination
              v-if="data.length"
              background
              class="mt-pagination"
              :current-page="page"
              :page-sizes="[8,16,32,100]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            />
          </el-tab-pane>
          <el-tab-pane label="添加Post" name="second">
            <el-form :model="temp" label-position="left" label-width="80px">
              <!--              <el-form-item label="title" v-if="action !== 'delete'">-->
              <!--                <el-input v-model="temp.title"></el-input>-->
              <!--              </el-form-item>-->
              <!--              <el-form-item label="结构" v-if="action !== 'delete'">-->
              <!--                <el-input type="textarea" v-model="temp.description"></el-input>-->
              <!--                &lt;!&ndash;<tinymce ref="tmmaterial" id="tmmaterial" :height="300" v-model="temp.description"></tinymce>&ndash;&gt;-->
              <!--              </el-form-item>-->
              <el-form-item v-if="action !== 'delete'" label="Post ID">
                <el-input v-model="temp.post_id" clearable type="number" placeholder="(选填)不填则会自动创建post" />
              </el-form-item>

            </el-form>
            <el-alert
              v-if="action === 'delete'"
              title="删除关联POST"
              type="error"
              :closable="false"
            />
            <el-button style="float: right;" :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/cms/topicpost'

import qs from 'qs'

// import Tinymce from '@/components/Tinymce'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  // components: { Tinymce },
  name: 'Topicpost',
  props: ['webVisible', 'topic_id', 'topic_title'],
  data() {
    return {
      viewDetail: false,
      viewTitle: '',
      viewdescription: '',
      activeName: 'first',
      data: [],
      listLoading: true,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 8,
      page: 1,
      total: 0,
      topic_data: {
        title: '',
        description: ''
      },
      action: null,
      dialogVisible: false,
      title: '',
      temp: {
        description: '',
        title: '',
        topic_id: ''
      },
      width: '',
      projects: [],
      innerDialogVisible: false
    }
  },
  watch: {
    webVisible(v) {
      this.dialogVisible = v
      if (v) {
        this.getList()
      }
    }
  },
  methods: {
    resetTemp() {
      this.temp = {
        description: '',
        title: ''
      }
      // console.log('create')
      // this.$nextTick(() => {
      //   this.$refs.tmmaterial.setContent('')
      // })
    },
    handleViewDetail(row) {
      this.viewTitle = row.title
      this.viewdescription = row.description
      this.viewDetail = true
    },
    handleClickTab(tab, event) {
      if (tab.name === 'second') {
        this.handleAction('create', '添加Post')
      }
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        topic_id: this.topic_id,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = row
          this.resetTemp()
          this.activeName = 'second'
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${row.title}?`
          this.temp = Object.assign({}, row)
          this.activeName = 'second'
          break
        case 'edit':
          this.title = `修改Post: ${row.title}`

          this.temp = Object.assign({}, row)
          this.activeName = 'second'
          // console.log(row)
          // this.$nextTick(() => {
          //   this.$refs.tmmaterial.setContent(row.description)
          // })
          break
      }
    },
    confirm() {
      this.temp.topic_id = this.topic_id
      const _data = this.temp
      switch (this.action) {
        case 'create':
          if (_data.topic_id === '') {
            alert('必须选择话题')
            return
          }
          Post({
            // title: _data.title,
            // description: _data.description,
            post_id: _data.post_id,
            topic_id: _data.topic_id

          }
          ).then(response => {
            this.innerDialogVisible = false
            this.activeName = 'first'
            this.getList()
            // this.notify('添加成功')
          })
          break
        case
          'delete'
          :
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.activeName = 'first'
            this.getList()
            this.notify('删除成功')
          })
          break
        case
          'edit'
          :
          Put(_data.id, {
            // title: _data.title,
            // description: _data.description,
            post_id: _data.post_id,
            topic_id: _data.topic_id
          }).then((response) => {
            this.innerDialogVisible = false
            this.activeName = 'first'
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      this.$emit('closeMetrialDialog', false)
    }
    // handleFetchTopic() {
    //   GetTopic(this.topic_id)
    //     .then(response => {
    //       this.topic_data = response.data.data
    //       console.log(this.topic_data)
    //     })
    //     .catch(e => {
    //       console.log('error')
    //     })
    // }
  }
  // created() {
  //   this.handleFetchTopic()
  // }
}
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .top >>> .el-select .el-input {
    width: 350px;
  }

  .top >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .top {
    padding-left: 0px;
    margin-bottom: 5px;
    margin-top: 2px;
  }

  .input-with-select {
    width: calc(100% - 200px);
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 150px
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 68px;
  }

  .mt-dialog >>> .el-transfer-panel {
    width: calc(50% - 60px);
  }

  .mt-form >>> .el-select {
    width: 100%;
  }

  .mt-form >>> .el-input__inner {
    width: 100%;
  }

  .mt-dialog >>> .el-dialog {
    margin: 10px auto !important;
  }

  .mt-dialog >>> .el-dialog__body {
    padding-bottom: 100px;
    padding-top: 5px;
  }

  .mt-dialog >>> .el-dialog__header {
    padding-bottom: 5px;
    padding-top: 10px;
  }
</style>
